<?php

use function Clue\StreamFilter\fun;
use Illuminate\Http\Request;
/**
 * encrypt_func 对信息进行加密处理
 *
 * @param string $CipherPlaintext 要加密的账号或密码明文
 * @param string $key 加密秘钥
 *
 * @return string 返回加密后的信息
 */
function encrypt_func($CipherPlaintext='',$key=''){
    $data = array();
    $CipherPlaintext=serialize($CipherPlaintext);
    $data['iv']=base64_encode(substr('fdakinel;injajdji',0,16));
    $data['value']=openssl_encrypt($CipherPlaintext, 'AES-256-CBC',$key,0,base64_decode($data['iv']));
    $encrypt=base64_encode(json_encode($data));
    return $encrypt;
}

/**
 * decrypt_func  解密函数
 *
 * @param string $encrypt 加密后的密文
 * @param string $key  解密秘钥
 *
 * @return int|mixed 返回解密后的信息，错误返回0
 */
function decrypt_func($encrypt ='',$key = ''){
    $encrypt = json_decode(base64_decode($encrypt), true);
    $str = base64_decode($encrypt['iv']);
    $decrypt = openssl_decrypt($encrypt['value'], 'AES-256-CBC', $key, 0, $str);
    $id = unserialize($decrypt);
    $id = $id ? $id : 0;
    return $id;
}

if (!defined('PASSWORD_BCRYPT')) {
    /**
     * PHPUnit Process isolation caches constants, but not function declarations.
     * So we need to check if the constants are defined separately from
     * the functions to enable supporting process isolation in userland
     * code.
     */
    define('PASSWORD_BCRYPT', 1);
    define('PASSWORD_DEFAULT', PASSWORD_BCRYPT);
    define('PASSWORD_BCRYPT_DEFAULT_COST', 10);
}

if (!function_exists('password_hash')) {

    /**
     * Hash the password using the specified algorithm
     *
     * @param string $password The password to hash
     * @param int    $algo     The algorithm to use (Defined by PASSWORD_* constants)
     * @param array  $options  The options for the algorithm to use
     *
     * @return string|false The hashed password, or false on error.
     */
    function password_hash($password, $algo, array $options = array()) {
        if (!function_exists('crypt')) {
            trigger_error("Crypt must be loaded for password_hash to function", E_USER_WARNING);
            return null;
        }
        if (is_null($password) || is_int($password)) {
            $password = (string) $password;
        }
        if (!is_string($password)) {
            trigger_error("password_hash(): Password must be a string", E_USER_WARNING);
            return null;
        }
        if (!is_int($algo)) {
            trigger_error("password_hash() expects parameter 2 to be long, " . gettype($algo) . " given", E_USER_WARNING);
            return null;
        }
        $resultLength = 0;
        switch ($algo) {
            case PASSWORD_BCRYPT:
                $cost = PASSWORD_BCRYPT_DEFAULT_COST;
                if (isset($options['cost'])) {
                    $cost = $options['cost'];
                    if ($cost < 4 || $cost > 31) {
                        trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING);
                        return null;
                    }
                }
                // The length of salt to generate
                $raw_salt_len = 16;
                // The length required in the final serialization
                $required_salt_len = 22;
                $hash_format = sprintf("$2y$%02d$", $cost);
                // The expected length of the final crypt() output
                $resultLength = 60;
                break;
            default:
                trigger_error(sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo), E_USER_WARNING);
                return null;
        }
        $salt_requires_encoding = false;
        if (isset($options['salt'])) {
            switch (gettype($options['salt'])) {
                case 'NULL':
                case 'boolean':
                case 'integer':
                case 'double':
                case 'string':
                    $salt = (string) $options['salt'];
                    break;
                case 'object':
                    if (method_exists($options['salt'], '__tostring')) {
                        $salt = (string) $options['salt'];
                        break;
                    }
                case 'array':
                case 'resource':
                default:
                    trigger_error('password_hash(): Non-string salt parameter supplied', E_USER_WARNING);
                    return null;
            }
            if (_strlen($salt) < $required_salt_len) {
                trigger_error(sprintf("password_hash(): Provided salt is too short: %d expecting %d", _strlen($salt), $required_salt_len), E_USER_WARNING);
                return null;
            } elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) {
                $salt_requires_encoding = true;
            }
        } else {
            $buffer = '';
            $buffer_valid = false;
            if (function_exists('mcrypt_create_iv') && !defined('PHALANGER')) {
                $buffer = mcrypt_create_iv($raw_salt_len, MCRYPT_DEV_URANDOM);
                if ($buffer) {
                    $buffer_valid = true;
                }
            }
            if (!$buffer_valid && function_exists('openssl_random_pseudo_bytes')) {
                $buffer = openssl_random_pseudo_bytes($raw_salt_len);
                if ($buffer) {
                    $buffer_valid = true;
                }
            }
            if (!$buffer_valid && @is_readable('/dev/urandom')) {
                $f = fopen('/dev/urandom', 'r');
                $read = _strlen($buffer);
                while ($read < $raw_salt_len) {
                    $buffer .= fread($f, $raw_salt_len - $read);
                    $read = _strlen($buffer);
                }
                fclose($f);
                if ($read >= $raw_salt_len) {
                    $buffer_valid = true;
                }
            }
            if (!$buffer_valid || _strlen($buffer) < $raw_salt_len) {
                $bl = _strlen($buffer);
                for ($i = 0; $i < $raw_salt_len; $i++) {
                    if ($i < $bl) {
                        $buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255));
                    } else {
                        $buffer .= chr(mt_rand(0, 255));
                    }
                }
            }
            $salt = $buffer;
            $salt_requires_encoding = true;
        }
        if ($salt_requires_encoding) {
            // encode string with the Base64 variant used by crypt
            $base64_digits =
                'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
            $bcrypt64_digits =
                './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

            $base64_string = base64_encode($salt);
            $salt = strtr(rtrim($base64_string, '='), $base64_digits, $bcrypt64_digits);
        }
        $salt = _substr($salt, 0, $required_salt_len);

        $hash = $hash_format . $salt;

        $ret = crypt($password, $hash);

        if (!is_string($ret) || _strlen($ret) != $resultLength) {
            return false;
        }

        return $ret;
    }

    /**
     * Get information about the password hash. Returns an array of the information
     * that was used to generate the password hash.
     *
     * array(
     *    'algo' => 1,
     *    'algoName' => 'bcrypt',
     *    'options' => array(
     *        'cost' => PASSWORD_BCRYPT_DEFAULT_COST,
     *    ),
     * )
     *
     * @param string $hash The password hash to extract info from
     *
     * @return array The array of information about the hash.
     */
    function password_get_info($hash) {
        $return = array(
            'algo' => 0,
            'algoName' => 'unknown',
            'options' => array(),
        );
        if (_substr($hash, 0, 4) == '$2y$' && _strlen($hash) == 60) {
            $return['algo'] = PASSWORD_BCRYPT;
            $return['algoName'] = 'bcrypt';
            list($cost) = sscanf($hash, "$2y$%d$");
            $return['options']['cost'] = $cost;
        }
        return $return;
    }

    /**
     * Determine if the password hash needs to be rehashed according to the options provided
     *
     * If the answer is true, after validating the password using password_verify, rehash it.
     *
     * @param string $hash    The hash to test
     * @param int    $algo    The algorithm used for new password hashes
     * @param array  $options The options array passed to password_hash
     *
     * @return boolean True if the password needs to be rehashed.
     */
    function password_needs_rehash($hash, $algo, array $options = array()) {
        $info = password_get_info($hash);
        if ($info['algo'] != $algo) {
            return true;
        }
        switch ($algo) {
            case PASSWORD_BCRYPT:
                $cost = isset($options['cost']) ? $options['cost'] : PASSWORD_BCRYPT_DEFAULT_COST;
                if ($cost != $info['options']['cost']) {
                    return true;
                }
                break;
        }
        return false;
    }

    /**
     * Verify a password against a hash using a timing attack resistant approach
     *
     * @param string $password The password to verify
     * @param string $hash     The hash to verify against
     *
     * @return boolean If the password matches the hash
     */
    function password_verify($password, $hash) {
        if (!function_exists('crypt')) {
            trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING);
            return false;
        }
        $ret = crypt($password, $hash);
        if (!is_string($ret) || _strlen($ret) != _strlen($hash) || _strlen($ret) <= 13) {
            return false;
        }

        $status = 0;
        for ($i = 0; $i < _strlen($ret); $i++) {
            $status |= (ord($ret[$i]) ^ ord($hash[$i]));
        }

        return $status === 0;
    }
}

if (!function_exists('_strlen')) {

    /**
     * Count the number of bytes in a string
     *
     * We cannot simply use strlen() for this, because it might be overwritten by the mbstring extension.
     * In this case, strlen() will count the number of *characters* based on the internal encoding. A
     * sequence of bytes might be regarded as a single multibyte character.
     *
     * @param string $binary_string The input string
     *
     * @internal
     * @return int The number of bytes
     */
    function _strlen($binary_string) {
        if (function_exists('mb_strlen')) {
            return mb_strlen($binary_string, '8bit');
        }
        return strlen($binary_string);
    }

    /**
     * Get a substring based on byte limits
     *
     * @see _strlen()
     *
     * @param string $binary_string The input string
     * @param int    $start
     * @param int    $length
     *
     * @internal
     * @return string The substring
     */
    function _substr($binary_string, $start, $length) {
        if (function_exists('mb_substr')) {
            return mb_substr($binary_string, $start, $length, '8bit');
        }
        return substr($binary_string, $start, $length);
    }

    /**
     * Check if current PHP version is compatible with the library
     *
     * @return boolean the check result
     */
    function check() {
        static $pass = NULL;

        if (is_null($pass)) {
            if (function_exists('crypt')) {
                $hash = '$2y$04$usesomesillystringfore7hnbRJHxXVLeakoG8K30oukPsA.ztMG';
                $test = crypt("password", $hash);
                $pass = $test == $hash;
            } else {
                $pass = false;
            }
        }
        return $pass;
    }

}

/**
 * getDiffDay 计算两个日期之前的天数
 *
 * @param $start  string 开始时间
 * @param $end    string 结束时间
 * @return int 相差天数
 */
/*function  getDiffDay($start,$end){
    $startrs = new \DateTime($start);
    $endrs = new \DateTime($end);
    $interval = $endrs->diff($startrs);
    $d = intval($interval->format("%d"));
    $h = intval($interval->format("%h"));
    $i = intval($interval->format("%i"));
    $totalMins = $d*24*60+$h*60+$i;
    return round($totalMins/1440,2);
}*/
function  getDiffDay($start,$end){
    $start = Carbon\Carbon::parse($start);
    $end   = Carbon\Carbon::parse($end);

    return round($end->diffInMinutes($start)/1440,2);
}
/**
 * setActive  给菜单增加高亮状态
 *
 * @param $routes mixed url路径
 * @param $output string 类名
 * @return boolean
 */
function setActive($routes, $output = "active")
{
    if(is_array($routes)){
        foreach ($routes as $route)
        {
            if (Route::currentRouteName() == $route) return $output;
        }
    }else{
        if (Route::currentRouteName() == $routes) return $output;
    }
    return true;
}

/**
 * setRightNav 后台管理右上方导航条公共防范
 * 
 * @param $position  string 要展示的位置
 * @return bool|mixed|string
 */
function setRightNav($position){
    if (empty($position)) return false;
        switch(Route::currentRouteName()){
            case 'admin.index':
                $return=['h1'=>'Dashboard ','small'=>'控制台','href'=>Route::currentRouteName(),'second'=>'Dashboard','third'=>''];
                break;
            case 'admin.ogz.index':
                $return=['h1'=>'组织机构列表 ','small'=>'','href'=>Route::currentRouteName(),'second'=>'组织机构管理','third'=>'组织机构列表'];
                break;
            case 'qyapp.index':
                $return=['h1'=>'企业应用列表 ','small'=>'','href'=>Route::currentRouteName(),'second'=>'企业应用管理 ','third'=>'企业应用列表'];
                break;
            case 'qyapp.addpage':
                $return=['h1'=>'企业应用列表 ','small'=>'','href'=>Route::currentRouteName(),'second'=>'企业应用管理 ','third'=>'添加'];
                break;
            case 'qyapp.editpage':
                $return=['h1'=>'企业应用列表 ','small'=>'','href'=>Route::currentRouteName(),'second'=>'企业应用管理 ','third'=>'修改'];
                break;
            case 'admin.flaw.vulslist':
                $return=['h1'=>'漏洞列表 ','small'=>'','href'=>Route::currentRouteName(),'second'=>'漏洞管理 ','third'=>'漏洞列表'];
                break;
            case 'admin.flaw.vulsadd':
                $return=['h1'=>'漏洞列表 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞管理 ','third'=>'提交漏洞'];
                break;
            case 'admin.flaw.vulsupdate':
                $return=['h1'=>'漏洞列表 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞管理 ','third'=>'更新漏洞'];
                break;
            case 'admin.flaw.levellist':
                $return=['h1'=>'等级评分 ','small'=>'','href'=>Route::currentRouteName(),'second'=>'等级评分 ','third'=>'等级列表'];
                break;
            case 'admin.flaw.leveladd':
                $return=['h1'=>'等级评分 ','small'=>'','href'=>'admin.flaw.levellist','second'=>'等级评分 ','third'=>'添加等级'];
                break;
            case 'admin.flaw.levelupdate':
                $return=['h1'=>'等级评分 ','small'=>'','href'=>'admin.flaw.levellist','second'=>'等级评分 ','third'=>'编辑等级'];
                break;
            case 'admin.flaw.index':
                $return=['h1'=>'漏洞分类 ','small'=>'','href'=>Route::currentRouteName(),'second'=>'漏洞分类 ','third'=>'分类列表'];
                break;
            case 'admin.flaw.add':
                $return=['h1'=>'漏洞分类 ','small'=>'','href'=>'admin.flaw.index','second'=>'漏洞分类 ','third'=>'添加分类'];
                break;
            case 'admin.flaw.update':
                $return=['h1'=>'漏洞分类 ','small'=>'','href'=>'admin.flaw.index','second'=>'漏洞分类 ','third'=>'更新分类'];
                break;
            case 'admin.access.user.index':
                $return=['h1'=>'用户管理 ','small'=>'','href'=>Route::currentRouteName(),'second'=>'用户管理 ','third'=>'用户列表'];
                break;
            case 'admin.access.role.index':
                $return=['h1'=>'角色管理 ','small'=>'','href'=>Route::currentRouteName(),'second'=>'角色管理 ','third'=>'角色列表'];
                break;
            case 'admin.access.role.add':
                $return=['h1'=>'角色管理 ','small'=>'','href'=>'admin.access.role.index','second'=>'角色管理 ','third'=>'授权角色'];
                break;
            case 'admin.access.role.update':
                $return=['h1'=>'角色管理 ','small'=>'','href'=>'admin.access.role.index','second'=>'角色管理 ','third'=>'更新权限'];
                break;
            case 'admin.access.permission.index':
                $return=['h1'=>'节点管理 ','small'=>'','href'=>Route::currentRouteName(),'second'=>'节点管理 ','third'=>'节点列表'];
                break;
            case 'admin.log.index':
                $return=['h1'=>'日志管理 ','small'=>'','href'=>Route::currentRouteName(),'second'=>'日志管理 ','third'=>'日志列表'];
                break;
            case 'admin.flaw.confirmShow':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞列表 ','third'=>'漏洞操作'];
                break;
            case 'admin.flaw.check':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞列表 ','third'=>'待审核'];
                break;
            case 'admin.flaw.ensure':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞列表 ','third'=>'待确认'];
                break;
            case 'admin.flaw.repair':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞列表 ','third'=>'待修复'];
                break;
            case 'admin.flaw.confirm':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞列表 ','third'=>'已修复'];
                break;
            case 'admin.flaw.solved':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞列表 ','third'=>'已解决'];
                break;
            case 'admin.flaw.shut':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞列表 ','third'=>'已关闭'];
                break;
            case 'admin.flaw.ignore':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞列表 ','third'=>'已忽略'];
                break;
            case 'admin.flaw.noEffect':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞列表 ','third'=>'无影响'];
                break;
            case 'admin.flaw.appeal':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞列表 ','third'=>'申诉中'];
                break;



            case 'admin.flaw.checkForm':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞列表 ','third'=>'漏洞审核'];
                break;
            case 'admin.flaw.ensureForm':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞列表 ','third'=>'漏洞确认'];
                break;
            case 'admin.flaw.appealForm':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞列表 ','third'=>'漏洞申诉'];
                break;
            case 'admin.flaw.repairForm':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞列表 ','third'=>'修复漏洞'];
                break;
            case 'admin.flaw.shutDownForm':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞列表 ','third'=>'关闭漏洞'];
                break;
            case 'admin.flaw.search':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞列表 ','third'=>'漏洞搜索'];
                break;
            case 'admin.flaw.vulsdetail':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.vulslist','second'=>'漏洞列表 ','third'=>'漏洞详情'];
                break;
            case 'admin.flaw.chartsanalysis':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.chartsanalysis','second'=>'parentcharts','third'=>''];
                break;
            case 'admin.flaw.subblock':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.chartsanalysis','second'=>'parentcharts','third'=>'childcharts'];
                break;
            case 'admin.flaw.company':
                $return=['h1'=>'漏洞管理 ','small'=>'','href'=>'admin.flaw.chartsanalysis','second'=>'parentcharts','third'=>'childcharts'];
                break;
            case 'admin.goods.goodslist':
                $return=['h1'=>'商品管理 ','small'=>'','href'=>'admin.goods.goodslist','second'=>'商品管理','third'=>'商品列表'];
                break;
            case 'admin.goods.goodsadd':
                $return=['h1'=>'添加商品 ','small'=>'','href'=>'admin.goods.goodslist','second'=>'商品管理','third'=>'商品列表'];
                break;
            case 'admin.goods.goodsupdate':
                $return=['h1'=>'更新商品 ','small'=>'','href'=>'admin.goods.goodslist','second'=>'商品管理','third'=>'商品列表'];
                break;
            case 'admin.goods.goodscatelist':
                $return=['h1'=>'分类管理 ','small'=>'','href'=>'admin.goods.goodscatelist','second'=>'分类管理','third'=>'分类列表'];
                break;
            case 'admin.goods.goodcatesadd':
                $return=['h1'=>'添加分类 ','small'=>'','href'=>'admin.goods.goodscatelist','second'=>'分类管理','third'=>'分类列表'];
                break;
            case 'admin.goods.goodscateupdate':
                $return=['h1'=>'更新分类 ','small'=>'','href'=>'admin.goods.goodscatelist','second'=>'分类管理','third'=>'分类列表'];
                break;
            //公告部分
            case 'admin.announce.index':
                $return=['h1'=>'公告管理 ','small'=>'','href'=>'admin.announce.index','second'=>'公告列表','third'=>''];
                break;
            case 'admin.announce.new':
                $return=['h1'=>'公告管理 ','small'=>'','href'=>'admin.announce.new','second'=>'新增列表','third'=>''];
                break;
            case 'admin.announce.publish':
                $return=['h1'=>'公告管理 ','small'=>'','href'=>'admin.announce.publish','second'=>'发布公告','third'=>''];
                break;
            case 'admin.announce.modify':
                $return=['h1'=>'公告管理 ','small'=>'','href'=>'admin.announce.index','second'=>'公告列表','third'=>'修改公告'];
                break;
            case 'admin.announce.det':
                $return=['h1'=>'公告管理 ','small'=>'','href'=>'admin.announce.index','second'=>'公告列表','third'=>'公告详情'];
                break;
            //订单
            case 'admin.order.orderlist':
                $return=['h1'=>'兑换记录 ','small'=>'','href'=>'admin.order.orderlist','second'=>'订单列表','third'=>''];
                break;
            //漏洞分发
            case 'admin.distribute.index':
                $return=['h1'=>'我分发的 ','small'=>'','href'=>'admin.distribute.index','second'=>'列表','third'=>''];
                break;
            case 'admin.distribute.recived':
                $return=['h1'=>'分发给我的 ','small'=>'','href'=>'admin.distribute.recived','second'=>'列表','third'=>''];
                break;
            case 'admin.distribute.det':
                $return=['h1'=>'漏洞详情 ','small'=>'','href'=>'admin.distribute.det','second'=>'详情','third'=>''];
                break;
            //项目管理
            case 'admin.projectmanage.index':
                $return=['h1'=>'项目管理 ','small'=>'','href'=>'admin.projectmanage.index','second'=>'项目管理 ','third'=>'列表'];

                break;
            case 'admin.projectmanage.addpage':
                $return=['h1'=>'项目管理 ','small'=>'','href'=>'admin.projectmanage.index','second'=>'项目管理 ','third'=>'添加'];
                break;
            case 'admin.projectmanage.detail':
                $return=['h1'=>'项目管理 ','small'=>'','href'=>'admin.projectmanage.index','second'=>'项目管理 ','third'=>'详情'];
                break;
            case 'admin.projectmanage.updaterow':
                $return=['h1'=>'项目管理 ','small'=>'','href'=>'admin.projectmanage.index','second'=>'项目管理 ','third'=>'修改'];
                break;
            //测试项
            case 'admin.checkoption.index':
                $return=['h1'=>'测试项 ','small'=>'','href'=>Route::currentRouteName(),'second'=>'测试项 ','third'=>'列表'];

                break;
            case 'admin.checkoption.addpage':
                $return=['h1'=>'测试项 ','small'=>'','href'=>'admin.checkoption.index','second'=>'测试项 ','third'=>'添加'];
                break;
            case 'admin.checkoption.vuls':
                $return=['h1'=>'测试项漏洞 ','small'=>'','href'=>Route::currentRouteName(),'second'=>'测试项漏洞 ','third'=>'列表'];
                break;
            case 'knowledge.create':
                $return=['h1'=>'知识库 ','small'=>'','href'=>'knowledge.index','second'=>'知识库 ','third'=>'新增'];
                break;
            case 'knowledge.show':
                $return=['h1'=>'知识库 ','small'=>'','href'=>'knowledge.index','second'=>'知识库 ','third'=>'详情'];
                break;
            case 'knowledge.index':
                $return=['h1'=>'知识库 ','small'=>'','href'=>Route::currentRouteName(),'second'=>'知识库 ','third'=>'列表'];
                break;
            default:
                $return=['h1'=>'后台管理','small'=>'','second'=>'','third'=>''];
        }
//    }
    $return['home'] ='Home';
    switch ($position){
        case "h1";
            $str = $return['h1'];
            break;
        case "small";
            $str = $return['small'];
            break;
        case "href":
            $str = $return['href'];
            break;
        case "home";
            $str = $return['home'];
            break;
        case "second":
            $str = $return['second'];
            break;
        case "third":
            $str = $return['third'];
            break;
    }
    return $str;
}
/**
 * 多维数组转一维数组
 * @param array $arr
 */
function MultipleToOne ($arr){
    $resArr = [];
    foreach ($arr as $k => $v){

        if (is_array($v)){
            $resArr = array_merge($resArr,MultipleToOne($v));
        }else{
            $resArr[] = $v;
        }
    }
    return $resArr;
}


/**发送post请求
 * @param $url  请求地址
 * @param $post_data  请求数据
 */
function curlpost($url, $post_data){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}

/**
 * generateSn 生成商品编号
 *
 * @param $length int 長度
 * @return string
 */
function generateSn($length=18)
{
    if($length>36) $length = 36;
    if (function_exists('com_create_guid') === true) {
        return trim(com_create_guid(), '{}');
    }
    $sprintf = sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
    return substr($sprintf,0,$length);
}

/**
 * UseAjaxTips 如果是ajax请求，调用此方法返回json数据
 *
 * @param string $msg ajax返回的错误信息
 * @param bool $ajaxRequest
 *
 * @param int $code
 */
function UseAjaxTips($msg = '', $ajaxRequest = true, $code = 200){
    $jsonInfo = ['msg' => '信息错误', 'code' => 500];
    if($ajaxRequest){
        $jsonInfo = ['msg' => $msg, 'code' => $code];
    }
    die(collect($jsonInfo)->toJson());
}

/**
 * sendStreamFile 调用海航上传图片接口
 * 
 * @param $request object http请求
 * @param $file string 要上传的文件
 * @param string $user string 用户信息
 * 
 * @return null
 */
function sendStreamFile($request, $file, $user ="test"){
    $apiUrl = "http://".env('WATERMARKIP').":".env('WATERMARKPORT')."/wms/api/sendsource.json";
    $data =array(
        'type' => pathinfo($file,PATHINFO_EXTENSION),
        'clientip' => $request->getClientIp(),
        'clientuser' => $user,
        'clientuseragent' => $request->header('User-Agent'),
    );
    $resid = null;
    //将远程图片转成本地，加快访问速度
    //$fileLocal = preg_replace('#(http|https):\/\/'.$_SERVER['HTTP_HOST'].'(\/?('.env("APP_ROOT").'))\/?#i','',$file);
    $fileLocal = preg_replace('#'.env("APP_URL").'(\/?('.env("APP_ROOT").'))\/?#i','',$file);
    \Log::info('beforeRep:'.$file ."\nafterRep:".$fileLocal);
    try{
        $resource = fopen($fileLocal, 'r');
    }catch (\Exception $e){
        \Log::info($e->getMessage());
        return false;
    }
    if ($resource){
        $stream = GuzzleHttp\Psr7\stream_for($resource);
        $client = new GuzzleHttp\Client();
        $request = new GuzzleHttp\Psr7\Request(
            'POST',
            $apiUrl,
            ['form_params' => $data],
            new GuzzleHttp\Psr7\MultipartStream(
                [
                    [
                        'name' => 'bigfile',
                        'contents' => $stream,
                    ],
                ]
            )
        );
        $response = $client->send($request);
        $str_body = (string)$response->getBody();
        /*$jsonRes = null;
        while (!$body->eof()) {
            $jsonRes= $body->read(1024);
        }*/
        $res = json_decode($str_body);
        \Log::info('sendsource info is'.$str_body);

        if(isset($res->success) && $res->success){
            $resid =  $res->data->resid;
        }
    }
    return $resid;
}

/**
 * getWaterImagePath 获取添加水印后的图片地址
 *
 * @param $request object http请求
 * @param $file string 要上传的文件
 * @param string $user string 用户信息
 * 
 * @return null
 */
function getWaterImagePath($request, $file, $user ='test'){
    $resid = sendStreamFile($request, $file, $user);
    \Log::info('vul id '.$request->id.' and user '.$user.' picture watermark resid'.$resid);
    if(empty($resid)){
        \Log::info("resid is empty!");
        return null;
    }
    $apiUrl = "http://".env('WATERMARKIP').":".env('WATERMARKPORT')."/wms/api/getwm.json";
    $data =array(
        'strlevelname' => "security",
        'clientip' => $request->getClientIp(),
        'clientuser' => $user,
        'resid' => $resid,
        'clientuseragent' => $request->header('User-Agent'),

    );
    $client = new GuzzleHttp\Client();
    $r = $client->request('POST', $apiUrl, ['form_params' => $data,'debug'=>false]);
    $body = $r->getBody();
    $res = json_decode($body->getContents());
    \Log::info('getwm info is'.json_encode($res));
    $imgPath = null;
    if(isset($res->success) && $res->success){
        $imgPath =  $res->data->imgurl;
    }
    return $imgPath;
}

/**
 * overwriteConetnt 对内容中的图片进行水印处理
 *
 * @param $request object http请求
 * @param $content string 要加密的内容
 * @param string $user string 用户信息
 *
 * @return mixed
 */
function overwriteConetnt($request, $content, $user){
    $cache = \Cache::get($request->id.'_'.$user.'cacheReplaceObj');
    if(is_null($cache)){
        preg_match_all('/< *img[^>]*src *= *["\']?([^"\']*)>?/i', $content, $matches);
        $replaceObj = $content;
        $host = $request->getHost();
        if(is_array($matches[1])){
            foreach ($matches[1] as $k=>$v){
                \Log::info('img path'.$v);
                //部分是绝对路径
                if (strpos($v,$host)){
                    //外网图片不做水印
                    if (strpos($host,env('APP_URL'))){
                        continue;
                    }
                    $file = $v;
                }else{
                    $file = rtrim(env('APP_URL'),'/') . '/' . ltrim($v,'/');
                }
                try{

                    $waterImage = getWaterImagePath($request,$file , $user);
                    if(!is_null($waterImage)) {
                        $newcontent = preg_replace('#' . $matches[0][$k] . '#i', '<img src="' . $waterImage, $replaceObj);
                        $replaceObj = $newcontent;
                    }
                }catch (\Exception $e){
                    \Log::info($e->getMessage());
                }
            }
        }else{
            if (strpos($matches[1],$host)>=0){
                //外网图片不做水印
                if (strpos($host,env('APP_URL'))){
                    return $replaceObj;
                }
                $file = $matches[1];
            }else{
                $file = rtrim(env('APP_URL'),'/') . '/' . ltrim($matches[1],'/');
            }
            try{
                $waterImage = getWaterImagePath($request, $file, $user);
                if(!is_null($waterImage)){
                    $replaceObj = preg_replace('/< *img[^>]*src *= *["\']?([^"\'].*)>"?$/i', '<img src="'.$waterImage.'">', $content);
                }
            }catch (\Exception $e){
                \Log::info($e->getMessage());
            }
        }
        \Cache::put($request->id.'_'.$user.'cacheReplaceObj', $replaceObj, 10);

    }else{
        $replaceObj = \Cache::get($request->id.'_'.$user.'cacheReplaceObj');
    }
    return $replaceObj;
}

/**
 * 获取客户端ip
 * @return string
 */
function getClientIp(){
    //strcasecmp 比较两个字符，不区分大小写。返回0，>0，<0。

    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $ip = getenv('REMOTE_ADDR');
    } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    $ip = str_replace('::1','127.0.0.1',$ip);
    $res =  preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
    return $res;
}

/**
 * 返回上午下午
 */
function getStrTime(){
    $no=date("H",time());
    if ($no>0&&$no<=6){
        return "凌晨好";
    }
    if ($no>6&&$no<12){
        return "上午好";
    }
    if ($no>=12&&$no<=18){
        return "下午好";
    }
    if ($no>18&&$no<=24){
        return "晚上好";
    }
    return "您好";
}
